﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fly.Common.Helper
{
    /// <summary>
    /// 字节扩展类
    /// </summary>
    public static class ByteHelper
    {
        #region 把8位字节数组转换成Base64字符串

        /// <summary>
        /// 把8位字节数组转换成Base64字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToBase64(this Byte[] bytes)
        {
            try
            {
                return Convert.ToBase64String(bytes);
            }
            catch
            {
                return null;
            }
        }

        #endregion

        #region 文件大小转换

        /// <summary>
        /// 将指定的大小转换为可读的文件大小的表示方式(KB MB GB TB PB EB)
        /// </summary>
        /// <param name="bytes">以字节为单位的长度</param>
        /// <returns>转换后可读的文件大小</returns>
        public static string ToFileSize(long bytes)
        {
            const int unit = 1024;
            if (bytes < unit) return bytes + " B";
            int exp = (int)(Math.Log(bytes) / Math.Log(unit));
            return String.Format("{0:F1} {1}B", bytes / Math.Pow(unit, exp), "KMGTPE"[exp - 1]);
        }

        #endregion
    }
}
